import java.io.*;
import java.text.*;

public class Encrypter {
	private static final int row = 50;
	private static final int column = 80;
	private static final String currentDirectory = System.getProperty("user.dir") + "/";
	private static final String messageDirectory = currentDirectory + "plainTextInput/";
	private static final String cipherTextDirectory = currentDirectory + "cipherText/";
	private static final String padDirectory = currentDirectory + "padFilesGenerated/";
	private String[] plainTexts;
	private String[] padFiles;
	
	public Encrypter(String plainTextList) {
		plainTexts = plainTextList.split(",");
        // NOTE: had to change the input b/c of presence of .svn directory
        String[] padFilesTemp;
		padFilesTemp = new File(padDirectory).list();
        this.padFiles = new String[padFilesTemp.length - 1];
        for(int i = 0; i < padFilesTemp.length - 1; i++) {
            padFiles[i] = (i + 1) + ".txt";
        }
        for(int i = 0; i < padFiles.length; i++) {
            System.out.println(padFiles[i]);
        }
	}
	
	public void encrypt() {
		try {
			checkDirectory(cipherTextDirectory);
			NumberFormat nf = new DecimalFormat("0");
			for (int i = 0; i < plainTexts.length; i++) {
//			for (String plainText : plainTextList.split(",")) {
				byte[] m = readFile(messageDirectory + plainTexts[i]);
				byte[] p = readFile(padDirectory + padFiles[i%padFiles.length]);
				byte[] c = new byte[row * column];
				for (int j = 0; j < (row * column); j++) {
					byte value = (byte)(((m[j]-32)+(p[j]-32))%95);
					if (value < 0) { value += 95; }
					c[j] = (byte)(value + 32);
				}
				writeFile(cipherTextDirectory + "c" + nf.format(i+1), c);
			}
		} catch (Exception e) { System.err.println("ERROR: " + e); }
	}

	private void checkDirectory(String directory) {
		File d = new File(directory);
		if (!d.exists()) { d.mkdir(); }
		String[] f = d.list();
		for (int i = 0; i < f.length; i++) { new File(d, f[i]).delete(); }
	}
	
	private byte[] readFile(String fileName) throws Exception {
		byte[] retVal = new byte[row * column];
			FileInputStream fis = new FileInputStream(fileName);
			fis.read(retVal);
			fis.close();
		return retVal;
	}
	
	private void writeFile(String fileName, byte[] b) throws Exception {
			FileOutputStream fos = new FileOutputStream(fileName + ".txt");
			fos.write(b);
			fos.close();
	}
}
